// @flow
/**
 * 在这里处理response status code
 */

import fetch from 'isomorphic-fetch'
// import merge from 'lodash.merge'
// import R from 'ramda'

type Params = {
  path: string,
  options: Object
}

type Store = {
  dispatch: () => void,
  getState: () => Object
}

function setParams (params: Params, store?: Store) {
  return Promise.resolve(params)
}

function handleFetch ({ path, options }: Params) {
  return fetch(path, options)
}

export function handleFetchError (e: Error, title: string = '请求异常') {
  // console.error(e)
  const ErrMessage = e && e.message || e
  let errInfo
  let MatchErr = false
  try {
   // $FlowFixMe
    errInfo = JSON.parse(ErrMessage)
    MatchErr = true
  } catch (e) {
    errInfo = ErrMessage
    MatchErr = false
  }
  console.log('请求异常')
  // console.log(errInfo)
  // console.log(MatchErr)
  if (MatchErr && (errInfo.code === 400102)) {
    localStorage.setItem('asset_token', '')
    // const origin = window.location.origin
    window.location.href = '/login'
    // if (!__TEST__) {
    //   if (__DEV__) {
    //     window.location.href = 'http://localhost:3000/login'
    //   } else {
    //     window.location.href = origin.replace('console.', '') + '/login'
    //   }
    // }
  }
}

function isResError ({ status }: Object) {
  return status >= 400
}

function handleResponseStatus (response) {
  if (isResError(response)) {
    // TODO: handle http error
  }

  return response
}
export function LoginFetch (path: string, options: Object = {}, store?: Store) {
  const params = { path, options }
  return setParams(params, store)
    .then(handleFetch)
    .then(handleResponseStatus)
}

export function universalFetch (path: string, options: Object = {}, store?: Store) {
  const token = localStorage.getItem('asset_token')
  // X-Auth
  // const headers = {
  //   'X-Auth': token
  // }
  // let headers = Object.assign({}, { 'X-Auth': token })
  let headers = Object.assign({}, options.headers, { 'X-Auth': token })

  const newOptions = Object.assign({}, options, { headers })
  const params = { path, options: newOptions }
  // console.log(params)
  return setParams(params, store)
    .then(handleFetch)
    .then(handleResponseStatus)
}

export default universalFetch
